import { login } from '@/api/user'
import router from '@/router'
import { ACCESS_TOKEN } from '../../mutation-types'
import { ThunkResult } from '../../types/store'

export function Login(username: string, password: string): ThunkResult<Promise<any>> {
  return (dispatch, getState) => {
    return new Promise((resolve, reject) => {
      login({ username, password })
        .then(res => {
          const data = res.data
          localStorage.setItem(ACCESS_TOKEN, data.token)
          dispatch({
            type: 'user/modify',
            payload: { id: data.id, name: data.name }
          })
          resolve(data)
        })
        .catch(e => reject(e))
    })
  }
}

export function Logout(): ThunkResult<Promise<boolean>> {
  return dispatch => {
    return new Promise(resolve => {
      localStorage.removeItem(ACCESS_TOKEN)
      dispatch({ type: 'user/reset' })
      setTimeout(() => router.push('/user/login'))
      resolve(true)
    })
  }
}
